<?php

namespace app\merchant\controller\content;

use app\merchant\controller\Base;
use app\merchant\model\Article as ArticleModel;
use app\merchant\model\article\Category as CategoryModel;

/**
 * 文章管理控制器
 * Class article
 * @package app\merchant\controller\content
 */
class Article extends Base
{
    /**
     * 文章列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $model = new ArticleModel;
        $list = $model->getList();
        return $this->renderSuccess($list,"查询成功");

    }

    /**
     * 文章分类
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function catgory()
    {
        $list = CategoryModel::getAll();
        return $this->renderSuccess($list,"查询成功");

    }


    /**
     * 添加文章
     * @return array|mixed
     */
    public function add()
    {
        $model = new ArticleModel;

        // 新增记录
        if ($model->add($this->postData())) {
            return $this->renderSuccess([],'添加成功');
        }
        return $this->renderError([],$model->getError() ?: '添加失败');
    }

    /**
     * 更新文章
     * @param $article_id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        $param = $this->postData();
        if (!isset($param['article_id']) || isInt($param['article_id'])) {
           return $this->renderError([],"参数错误");
        }
        // 文章详情
        $model = ArticleModel::detail($param['article_id']);
        if (empty($model)) {
            return $this->renderError([],"文章不存在，请刷新重试");
        }

        // 更新记录
        if ($model->edit($param)) {
            return $this->renderSuccess([],'更新成功');
        }
        return $this->renderError([],$model->getError() ?: '更新失败');
    }

    /**
     * 删除文章
     * @param $article_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function delete()
    {
        $param = $this->postData();
        if (!isset($param['article_id']) || isInt($param['article_id'])) {
            return $this->renderError([],"参数错误");
        }
        // 文章详情
        $model = ArticleModel::detail($param['article_id']);
        if (empty($model)) {
            return $this->renderError([],"文章不存在，请刷新重试");
        }

        if (!$model->setDelete()) {
            return $this->renderError([],$model->getError() ?: '删除失败');
        }
        return $this->renderSuccess([],'删除成功');
    }

}